import $C from '../config.js'
import Vue from 'vue'
let time = Date.parse(new Date()) / 1000
class miniappToken {
	constructor() {
		this.loginUrl = $C.api_url + 'sapi/auth/miniAppLogin';
		this.verifyUrl = $C.api_url + 'sapi/auth/verifytoken';
		this.getInfo = $C.api_url + 'sapi/auth/userInfo';
	}
	
	//初始化登陆
	async verify() { 
		const swtich=1;
		let merge_mode = 3//1自动获取token 3手动获取token
		let token = uni.getStorageSync('token'); //获取缓存
		let that = this;
		console.log('miniapp-token:'+token)
		
		if (!token) {
			//向微信api拿code，再向tp的api拿token
			this.getTokenFromServer();
		} else {
			//验证token是否过期，过期调用.getTokenFromServer函数获取
			this._veirfyFromServer(token); 
		}
		
	}
	
	//验证token
	_veirfyFromServer(token) {
		var that = this;
		uni.request({
			url: that.verifyUrl,
			method: 'POST',
			data: {
				token: token
			},
			success: function(res) {
				var valid = res.data.data.isValid;
				if (!valid) {
					that.getTokenFromServer();
				}
			}
		})
	}
	//获取Token
	getTokenFromServer() {
		var that = this;
		uni.login({
			provider: 'weixin',
			success: function(res) {
				uni.request({
					url: that.loginUrl,
					method: 'POST',
					data: {
						code: res.code,
						origin:'miniapp',
						loginType:'auto'
					},
					success: function(res2) {
						
						uni.setStorageSync('token', res2.data.data.token);
						let arr={}
						arr['data'] = res2.data.data.my
						arr['save_time']=time
						uni.setStorageSync('my', arr);
					}
				})
			}
		})
	}
}
export {
	miniappToken
};